<?php
/**
 * 将disqus评论数据导入到本地数据库中
 * 
 * */

require_once 'api/disqus.php';

class Import {
	
	private $site;
	private $site_api_key;
	private $start_id;
	private $db;
	
	public function __construct( $db, $site, $site_api_key, $start_id = 0 ){
		$this->db = $db;
		$this->site = $site;
		$this->site_api_key = $site_api_key;
		$this->start_id = $start_id ? $start_id : $this->getMaxId();
	}

	/**
	 * 取得站点disqus评论的最大id
	 * */
	public function getMaxId(){
		$sql = "SELECT MAX(disqus_id) AS max_id FROM ".DB_TABLE_PRE."comment WHERE site='{$this->site}'";
		$ret = $this->db->getOne( $sql );
		return empty( $ret ) ? 0 : $ret['max_id'];
	}
	
	/**
	 * 取得API返回的评论数据
	 * */
	public function getApiData(){
		$disqus = new DisqusAPI( null, $this->site_api_key );
		$data = $disqus->get_forum_posts('', array('filter'=>'approved','order'=>'asc','limit'=>100,'start_id'=>$this->start_id+1) );
		return $data;
	}
	
	/**
	 * 同步评论数据
	 * */
	public function synComment( $table, $field ){
		$arr = $dq = array();
		$data = $this->getApiData();
		
		foreach( $data as $k=>$v ){
			if( $v->status != 'approved'  ) continue;
			
			$arr[$k]['disqus_id']= $dq[] = $v->id;
			$arr[$k]['site']	= strtolower( $v->thread->forum_obj->name );
			$arr[$k]['url_md5']	= md5($v->thread->url);	
			$arr[$k]['url']		= $v->thread->url;
			$arr[$k]['author']	= addslashes( $v->author->username ?  $v->author->username : ($v->anonymous_author->name ? $v->anonymous_author->name : 'anonymous' ) );
			$arr[$k]['message']	= addslashes( $v->message );
			$arr[$k]['time']	= str_replace( 'T', ' ', $v->created_at);
			
			$u = explode('/', $v->thread->url);
			$n = end( $u );
			
			$sql = "SELECT D_ID, Field_{$field} AS aid FROM Table_{$table} WHERE url LIKE '%/{$n}'";
			$d = $this->db->getOne( $sql );
			$arr[$k]['d_id'] = $d['D_ID'];
			$arr[$k]['article_id'] = $d['aid'];
		}	
	
		if( !empty( $arr ) ){
			$this->db->insert('comment', $arr, 2);
		}
		
		if( count( $dq ) == 100 ){
			$this->start_id = $this->getMaxId();
			$this->synComment();
		}
		
		return $dq;
	}
	
	
}

